package com.zryc.controller;

import com.zryc.service.ProductService;
import com.zryc.shop.entity.Product;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/product")
@Slf4j
@Api(tags = "商品信息接口")
public class ProductController {
    @Autowired
    private ProductService productService;
    //调用这个请求修改库存
//    @RequestMapping(value = "/reduceInventory",method = RequestMethod.POST)
    @PostMapping(value = "/reduceInventory")
    @ApiOperation(value = "减少库存")
    //ApiOperation是加载方法的参数上
    public  void reduceInventory(@RequestParam("pid") @ApiParam(name = "pid", value = "商品的ID", example = "1", required = true) Integer pid,
                                 @RequestParam("num") @ApiParam(name = "num", value = "购买商品的数量", example = "2", required = true) Integer num){
        productService.reduceInventory(pid,num);
    }

    /**
     *  增加商品的接口
     * @param product 将商品信息封装到商品对象中
     * @return
     */
    @PostMapping(value = "/add",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "管理员增加商品的接口")
    public String add(@RequestBody Product product){
        if (productService.save(product)){
            return "OK";
        }else{
            return "FAIL";
        }

    }

    @GetMapping("/{pid}")
    @ApiOperation("使用商品ID查询商品详情")
    public ResponseEntity<Product> product(@PathVariable("pid") Integer pid, HttpServletRequest request){
        log.info("当前提供服务的端口是"+request.getServerPort());//在控制台打印端口号用于测试
        if (pid!=null && pid > 0){
            ResponseEntity<Product> responseEntity=ResponseEntity.ok(productService.getById(pid));
            return responseEntity;
        }else{
            return null;
        }
    }


}
